import { defineStore } from 'pinia'
import { ref } from 'vue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'
import { appoxUtility } from '@/appox/appox'
import { AppoxSecondProfilePack } from '@/appox/appox'

export const useBusChannelsStore = defineStore('busChannels', () => {
  // 状态
  const channelStatuses = ref(Array(48).fill('---'))
  const isUpdating = ref(false)

  // 数据
  let secondProfileBuffers = Array.from({ length: 48 }, () => [])

  // 动作
  async function updateChannelStatuses() {
    if (isUpdating.value) return
    isUpdating.value = true

    let running = await agencyAsync.getAppStatus() == appoxEnums.ApplicationStatus.Running

    if (!running) {
      channelStatuses.value = Array(48).fill('---')
      isUpdating.value = false
      return
    }

    let interest = appoxUtility.getInterestTimeLocal()
    const promises = Array.from({ length: 48 }, (_, i) => 
      agencyAsync.getBusChannelStatus(i + 1, 1000)
    )
    const statusResults = await Promise.all(promises)
    
    for (let i = 0; i < 48; i++) {
      let searchResult = appoxUtility.searchSample(secondProfileBuffers[i], interest, 1.0)
      if (searchResult) {
        let secondProfile = searchResult.weight1 > searchResult.weight2 ? searchResult.sample1 : searchResult.sample2
        channelStatuses.value[i] = secondProfile.availableCount + " / " + secondProfile.sourceCount
      }
      else {
        channelStatuses.value[i] = statusResults[i] ? 'O' : 'X'
      }
    }

    isUpdating.value = false
  }

  function onResetData() {
    secondProfileBuffers = Array.from({ length: 48 }, () => [])
  }

  function onInputData(data) {
    if (data instanceof AppoxSecondProfilePack) {
      for (const [channelID, sample] of Object.entries(data.profiles)) {
        if (channelID.startsWith('bus@')) {
          const channelIndex = parseInt(channelID.substring(4)) - 1 // 将bus@1转换为索引0
          if (channelIndex >= 0 && channelIndex < 48) {
            secondProfileBuffers[channelIndex].push(sample)
            appoxUtility.clipSampleBuffer(secondProfileBuffers[channelIndex])
          }
        }
      }
    }
  }

  return {
    // 状态
    channelStatuses,
    isUpdating,
    // 动作
    updateChannelStatuses,
    onResetData,
    onInputData
  }
}) 